package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"month/model/mysql"
	"month/model/redis"
	"strconv"
	"time"

	"month/userrpc/internal/svc"
	"month/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ProductListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewProductListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ProductListLogic {
	return &ProductListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ProductListLogic) ProductList(in *userrpc.ProductListRequest) (*userrpc.ProductListResponse, error) {
	// todo: add your logic here and delete this line

	NumLoc := "productList" + strconv.Itoa(int(in.Page)) + strconv.Itoa(int(in.PageSize)) + in.Name + in.OrderBy + in.OrderStore

	result, err := redis.Rdb.Get(NumLoc).Result()
	s, _ := redis.Rdb.Get("SumList").Result()
	var ProductList []mysql.Products
	var count int64
	if err != nil {
		query := mysql.DB.Debug().Model(&mysql.Products{})

		if in.Name != "" {
			query = query.Where("name like ?", "%"+in.Name+"%")
		}

		if in.OrderBy != "" {
			order := in.OrderBy
			if in.OrderStore == "desc" {
				order += " desc"
			} else {
				order += " asc"
			}
			query = query.Order(order)
		} else {
			query = query.Order("price desc").Order("created_at desc")
		}

		query.Count(&count)

		offset := (in.Page - 1) * in.PageSize

		err = query.Offset(int(offset)).Limit(int(in.PageSize)).Find(&ProductList).Error

		if err != nil {
			return nil, fmt.Errorf("展示失败")
		}

		marshal, _ := json.Marshal(&ProductList)
		bytes, _ := json.Marshal(&count)
		redis.Rdb.Set(NumLoc, string(marshal), time.Hour*24)
		redis.Rdb.Set("SumList", string(bytes), time.Hour*24)
		fmt.Println("走mysql")
	} else {
		json.Unmarshal([]byte(result), &ProductList)
		json.Unmarshal([]byte(s), &count)
		fmt.Println("走redis")
	}

	var sli []*userrpc.ProductList
	for _, m := range ProductList {
		one := userrpc.ProductList{
			Num:    m.Num,
			Name:   m.Name,
			Price:  float32(m.Price),
			Money:  float32(m.Money),
			Image:  m.Image,
			UserId: int64(m.UserId),
			Like:   int64(m.Like),
			Id:     int64(m.ID),
		}
		sli = append(sli, &one)
	}

	return &userrpc.ProductListResponse{List: sli, Sum: count}, nil
}
